package com.codeoss.framework.view.pagebean.mobile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.codeoss.framework.context.YunContext;
import com.codeoss.framework.converter.IConverter;
import com.codeoss.framework.converter.IConverterStore;
import com.codeoss.framework.data.metadata.Column;
import com.codeoss.framework.data.metadata.Query;
import com.codeoss.framework.data.metadata.Restrictions;
import com.codeoss.framework.data.metadata.Table;
import com.codeoss.framework.data.metadata.TableData;
import com.codeoss.framework.data.store.ITableStore;
import com.codeoss.framework.util.StringUtils;
import com.codeoss.framework.view.component.IDataBindSource;
import com.codeoss.framework.view.component.IDataBinding;
import com.codeoss.framework.view.component.IFormFieldExpression;
import com.codeoss.framework.view.component.IVarName;
import com.codeoss.framework.view.component.Page;
import com.codeoss.framework.view.component.store.IComponentStore;
import com.codeoss.framework.view.datasource.DataSourceConfig;
import com.codeoss.framework.view.pagebean.base.BasePageBean;
import com.codeoss.framework.view.pagebean.crud.PageBeanCRUDUtil;
import com.codeoss.framework.view.pagebean.crud.SelectRequest;
import com.codeoss.framework.view.pagebean.crud.SelectResponse;
import com.codeoss.framework.view.service.IVariableService;
import com.codeoss.framework.view.util.ComponentDataUtil;
import com.codeoss.framework.view.util.DataSourceUtil;
import com.codeoss.framework.view.util.PageBeanUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

@Service("mDetailPageBean")
public class MDetailPageBean extends BasePageBean{
	public static final String KEY_FORM_FIELD_LIST = "key_form_field_list";
	@Autowired
	private IVariableService variableService;
	@Autowired
	private ITableStore tableStore;
	@Autowired
	private IConverterStore converterStore;
	@Autowired
	private DataSourceUtil dataSourceUtil;
	@Autowired
	private PageBeanUtil pageBeanUtil;
	@Autowired
	private PageBeanCRUDUtil pageBeanCRUDUtil;
	@Autowired
	private ComponentDataUtil componentDataUtil;
	@Autowired
	private IComponentStore componentStore;
	@Autowired
	private ObjectMapper objectMapper;
	public void init() {
		YunContext yunContext = YunContext.getCurrentContext();
		Page page = yunContext.getPage();

		List<IDataBinding> formDataBindingList = new ArrayList<IDataBinding>();
		pageBeanUtil.getFormFieldList(page, formDataBindingList);
		page.setAttribute(KEY_FORM_FIELD_LIST, formDataBindingList);
		
		String action = yunContext.getQueryMap().get("action");
		processParentPagePara();
		if ("dataNew".equals(action)) {
			dataNew();
			return;
		} else if ("dataEdit".equals(action)) {
			String sId = yunContext.getQueryMap().get("id");
			String sMainDataSource = ((IDataBindSource)formDataBindingList.get(0)).getDataSource();
			DataSourceConfig mainDataSourceConfig = dataSourceUtil.getDataSourceConfigById(yunContext.getPage(),
					sMainDataSource);
			String sDirty= yunContext.getQueryMap().get("__dirty");
			if("true".equals(sDirty) || StringUtils.isEmpty(sId)) {
				Table table=tableStore.get(mainDataSourceConfig.getTableName());
				for (int i = 0; i < formDataBindingList.size(); i++) {
					IDataBinding dataBinding=formDataBindingList.get(i);
					
					if(yunContext.getQueryMap().containsKey("___"+dataBinding.getDataField())) {
						String sValue=yunContext.getQueryMap().get("_"+dataBinding.getDataField());
						if(!StringUtils.isEmpty(sValue)) {
							Column column=table.getColumnByColumnName(dataBinding.getDataField());
							 IConverter converter=converterStore.getConverter(column.getDataType());
							 Object value=converter.convertStringToObject(sValue);
							 variableService.setVariableValue(yunContext,((IVarName)dataBinding).getVarName(),value);
						}else {
							variableService.setVariableValue(yunContext,((IVarName)dataBinding).getVarName(),null);
						}
					}
				}
				pageBeanUtil.generateFormInfo(formDataBindingList);
			}else {
				com.codeoss.framework.data.metadata.Table table=tableStore.get(mainDataSourceConfig.getTableName());
				Column keyColumn=table.getPrimaryKeyColumn();
				IConverter converter=converterStore.getConverter(keyColumn.getDataType());
				variableService.setVariableValue(yunContext, mainDataSourceConfig.getTableName() + "_id",converter.convertStringToObject(sId));
				dataRefresh();
			}
		}
		
	}
	
	private void processParentPagePara() {
		YunContext yunContext = YunContext.getCurrentContext();
		Page page=yunContext.getPage();
		String parentCode="";
		String parentData="";
		if(!yunContext.isPostBack()) {
			parentCode=yunContext.getQueryMap().get("parentCode");
			parentData=yunContext.getQueryMap().get("parentData");
			yunContext.addPagePara("parentCode", parentCode);
			yunContext.addPagePara("parentData", parentData);
		}else {
			parentCode=yunContext.getViewRequest().getData().get(page.getId()+"_parentCode");
			parentData=yunContext.getViewRequest().getData().get(page.getId()+"_parentData");
		}
		if(parentCode==null) {
			return;
		}
		Page parentPage=componentStore.get(parentCode);
		List<IDataBinding> formDataBindingList=parentPage.getAttribute("key_form_field_list");
		try {
			ObjectNode objectNode = (ObjectNode) objectMapper.readTree(parentData);
			DataSourceConfig dataSourceConfig=parentPage.getDataSourceConfigById(((IDataBindSource)formDataBindingList.get(0)).getDataSource());
			Table table=tableStore.get(dataSourceConfig.getTableName());
			for (int i = 0; i < formDataBindingList.size(); i++) {
				IDataBinding dataBinding = formDataBindingList.get(i);
				JsonNode jsonNode = objectNode.get(dataBinding.getDataField());
				if (jsonNode != null) {
					String sValue = jsonNode.asText();
					Column column = table.getColumnByColumnName(dataBinding.getDataField());
					Object value = converterStore.getConverter(column.getDataType()).convertStringToObject(sValue);
					variableService.setVariableValue(yunContext, ((IVarName)dataBinding).getVarName(), value);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
	}
	
	public void dataNew() {
		YunContext yunContext = YunContext.getCurrentContext();
		Page page = yunContext.getPage();
		List<IDataBinding> formDataBindingList = page.getAttribute(KEY_FORM_FIELD_LIST);
		for (int i = 0; i < formDataBindingList.size(); i++) {
			IDataBinding dataBinding = formDataBindingList.get(i);
			if(dataBinding instanceof IFormFieldExpression) {
				Object  defaultValue=componentDataUtil.getDefaultValue(yunContext, page, (IFormFieldExpression)dataBinding);
				variableService.setVariableValue(yunContext,((IVarName)dataBinding).getVarName(), defaultValue);
			}else {
				variableService.setVariableValue(yunContext,((IVarName)dataBinding).getVarName(), null);
			}
		}
		pageBeanUtil.generateFormInfo(formDataBindingList);
	}
	
	public void dataRefresh() {
		YunContext yunContext = YunContext.getCurrentContext();
		Page page = yunContext.getPage();
		List<IDataBinding> formDataBindingList = page.getAttribute(KEY_FORM_FIELD_LIST);
		DataSourceConfig mainDataSourceConfig = dataSourceUtil.getDataSourceConfigById(yunContext.getPage(),
				((IDataBindSource)formDataBindingList.get(0)).getDataSource());
		Object idValue = variableService.getVariableValue(yunContext, mainDataSourceConfig.getTableName() + "_id");
		dataRefresh(idValue);
	}
	
	public void dataRefresh(Object idValue){
		YunContext yunContext = YunContext.getCurrentContext();
		Page page = yunContext.getPage();
		List<IDataBinding> formDataBindingList = page.getAttribute(KEY_FORM_FIELD_LIST);
		DataSourceConfig mainDataSourceConfig = dataSourceUtil.getDataSourceConfigById(yunContext.getPage(),
				((IDataBindSource)formDataBindingList.get(0)).getDataSource());
		Query query = new Query();
		if (idValue != null) {
			query.add(Restrictions.eq("id", idValue));
		} else {
			query.add(Restrictions.eq("id", -1));
		}
		com.codeoss.framework.data.metadata.Table table=tableStore.get(mainDataSourceConfig.getTableName());
		SelectRequest selectRequest=new SelectRequest();
		selectRequest.setMainTable(table);
		selectRequest.setMainQuery(query);
		SelectResponse  selectResponse=pageBeanCRUDUtil.select(yunContext, selectRequest);
		TableData tableData=selectResponse.getTableDataMap().get(table.getTableName());
		if (tableData.getData().size() > 0) {
			Map<String, Object> dataMap = (Map<String, Object>) tableData.getData().get(0);
			idValue = dataMap.get("id");
			yunContext.setCurrentId(idValue);
			for (int i = 0; i < formDataBindingList.size(); i++) {
				IDataBinding dataBinding = formDataBindingList.get(i);
				Object value = dataMap.get(dataBinding.getDataField());
				variableService.setVariableValue(yunContext, ((IVarName)dataBinding).getVarName(), value);
			}
		}
		pageBeanUtil.generateFormInfo(formDataBindingList);
	}
}
